//
//  DecorationLayer.cpp
//  DoutCakeMaker
//
//  Created by luotianqiang1 on 16/8/8.
//
//

#include "DecorationLayer.h"
#include "FoodData.h"
#include "LQ_adLoadingLayer.h"
#include "EatLayer.h"
#include "TouchMoveComponent.h"
#include "particleLayer.h"
#include "TouchNodeComponent.h"
USING_NS_KD;
REGIST_SECENE(DecorationLayer)

DecorationLayer::DecorationLayer(){
    _lockImage = "ui/getfree.png";
    eatContainer = nullptr;
    voiceSound = 0;
    isFirst = true;
    currentSprinkle = nullptr;
    autoShowBtnName.clear();
}

bool DecorationLayer::init(){
    if(BaseDecorationLayer::init()) {
        _chooseBg = Sprite::create("ui/ui_dec/icon.png");
        if(_chooseBg != nullptr)
            _chooseBg->retain();
        FoodData::clearDecoration();
        _operate = StudioLayer::create("DecorationLayer.csb");
        addChild(_operate);
        
        eatContainer = _operate->getNodeByName("eatContainer");
        
        
        _prompt = _operate->getNodeByName<Sprite*>("finger");
        
        auto _decBg = _operate->getNodeByName("icon_bg");
        auto size = _decBg->getContentSize();
        _decoView = MyScollView::create(getContentSize().width, 121);
        _decoView->setSpace(20);
        _decoView->setMarginLeft(10);
        _decoView->setDirection(MyScollView::Direction::HORIZONTAL);
        _decoView->setPosition(_decBg->getContentSize()*.5);
        _decBg->addChild(_decoView);
        _operate->getNodeByName<ui::ScrollView*>("ScrollView")->setScrollBarOpacity(0);
        auto hideNodes = {"btn_next","btn_reset","cup_shadow","icon_bg","cupDown","strawDec","cupDec"};
        for(auto name:hideNodes){
            auto node = _operate->getNodeByName(name);
            if(node)
                node->setVisible(false);
        }
        auto chisds = _operate->getNodeByName("ScrollView")->getChildren();
        for(auto btn:chisds){
            categoryNames.push_back(btn->getName());
            btn->setScale(0);
        }
        listView.selectClick  = CC_CALLBACK_2(DecorationLayer::select, this);
        listView.unSelectClick  = CC_CALLBACK_2(DecorationLayer::unSelect, this);
        
        auto inCupPath = FoodData::getInCupPath();
        _operate->changeNode("ice0", inCupPath[0]);
        auto eatClippinNode = ClippingNode::create();
        eatClippinNode->setAlphaThreshold(0.01f);
        eatContainer->addChild(eatClippinNode);
        auto mask = Sprite::create(inCupPath[0]);
        mask->setPosition(eatContainer->getContentSize()*.5);
        eatClippinNode->setStencil(mask);
        
        this->eatClippinNode = Sprite::create(inCupPath[1]);
        this->eatClippinNode->setPosition(eatContainer->getContentSize()*.5);
        eatClippinNode->addChild(this->eatClippinNode);
        auto spinkleTemp = Sprite::create(inCupPath[0]);
        spinkleTemp->setPosition(eatContainer->getContentSize()*.5);
        spinkleTemp->setVisible(false);
        this->eatClippinNode->addChild(spinkleTemp);
        spinkleTemp->setName("spinkleTemp");
        return true;
    }
    return false;
}

void DecorationLayer::select(ui::CheckBox*,size_t index){
    SoundPlayer::getInstance()->playEffect("sound/select.mp3");
    _operate->getNodeByName("icon_bg")->setVisible(true);
    creatIcon(index);
    showCatagore();
    eatContainer->removeComponent("TouchNodeComponent");
    auto childs = eatClippinNode->getChildren();
    for(auto child:childs){
        auto _TouchMoveComponent = child->getComponent("TouchMoveComponent");
        if(_TouchMoveComponent){
            _TouchMoveComponent->setEnabled(child->getName() == _currentcategory+"dec");
        }
        
    }
    if(_currentcategory != "sprinkle"){
        if(currentSprinkle != nullptr){
            currentSprinkle->setEnable(false);
            currentSprinkle = nullptr;
        }
    }
}
void DecorationLayer::unSelect(ui::CheckBox*,size_t index){
    hideCatagore();
    eatContainer->removeComponent("TouchNodeComponent");
    auto childs = eatClippinNode->getChildren();
    for(auto child:childs){
        auto _TouchMoveComponent = child->getComponent("TouchMoveComponent");
        if(_TouchMoveComponent){
            _TouchMoveComponent->setEnabled(false);
        }
        
    }
    if(currentSprinkle != nullptr){
        currentSprinkle->setEnable(false);
    }
    stopPrompt();
}

void DecorationLayer::touchEnd(ui::Widget* widget){
    BaseDecorationLayer::touchEnd(widget);
    if(widget->getName() == "btn_next"){
        _operate->setIsChange(true);
        auto path = FileUtils::getInstance()->getWritablePath()+"fileImage.png";
        Director::getInstance()->getTextureCache()->removeTextureForKey(path);
        auto size = eatContainer->getContentSize();
        auto pos = eatContainer->getPosition();
        auto an = eatContainer->getAnchorPoint();
        eatContainer->setPosition(Vec2::ZERO);
        eatContainer->setAnchorPoint(Vec2::ZERO);
        auto render = RenderTexture::create(size.width, size.height, Texture2D::PixelFormat::RGBA8888, GL_DEPTH24_STENCIL8);
        render->begin();
        eatContainer->visit();
        render->end();
        Director::getInstance()->getRenderer()->render();
        eatContainer->setPosition(pos);
        eatContainer->setAnchorPoint(an);
        render->saveToFile("fileImage.png");
        Director::getInstance()->getRenderer()->render();
        
        auto _endcallBack = [](){
            Director::getInstance()->popToRootScene();
            LQ_adLoadingLayer::loadingDoneCallback = nullptr;
              Director::getInstance()->pushScene(TransitionFade::create(0.8, EatLayer::createScene(), Color3B(47,150,180)));
        };
        if(IAPManager::getInstance()->isShowAds()){
            LQ_adLoadingLayer::loadingDoneCallback = _endcallBack;
            LQ_adLoadingLayer::showLoading<LQ_adLoadingLayer>(true);
        } else
            _endcallBack();
        isFirst = false;
        
    }
}
void DecorationLayer::onExitTransitionDidStart(){
    BaseDecorationLayer::onExitTransitionDidStart();
}
void DecorationLayer::onEnter(){
    BaseDecorationLayer::onEnter();
    if(isFirst) {
    }
}

void DecorationLayer::onEnterTransitionDidFinish(){
    BaseDecorationLayer::onEnterTransitionDidFinish();
    listView.setContainer(_operate->getNodeByName("ScrollView"));
    if(isFirst) {
        _eventDispatcher->setEnabled(false);
         SoundPlayer::getInstance()->playEffect("sound/general/ingredients_fly_in.mp3");
        auto cupDown = _operate->getNodeByName("cupDown");
        ActionHelper::showBezier(cupDown, cupDown->getPosition(), ActionHelper::ShowDirection::show_from_left,[this](){
            auto cup_shadow = _operate->getNodeByName("cup_shadow");
            cup_shadow->setVisible(true);
            cup_shadow->setOpacity(0);
            cup_shadow->runAction(FadeIn::create(0.2f));
        },0.9f);
        cupDown->setVisible(true);
        
        ActionHelper::delayFunc(0.4, this, [this](){
            auto node = _operate->getNodeByName("btn_next");
            ActionHelper::showBackInOut(node, node->getPosition(), ActionHelper::ShowDirection::show_from_right);
            node->setVisible(true);
            
            node = _operate->getNodeByName("btn_reset");
            ActionHelper::showBackInOut(node, node->getPosition(), ActionHelper::ShowDirection::show_from_left);
            node->setVisible(true);
             listView.getListView()->getInnerContainer()->setPositionX( listView.getListView()->getInnerContainer()->getPositionX()-400);
            auto bg_1 = _operate->getNodeByName("ScrollView");
            auto num = categoryNames.size();
            for(int i= num-1;i>=0;i--){
                auto btn = _operate->getNodeByName(categoryNames.at(i));
                if(btn)
                    btn->runAction(Sequence::create(DelayTime::create((num-1-i)*0.15),EaseExponentialOut::create(ScaleTo::create(0.3, 1)),CallFunc::create([=](){
                        if(i==0){
                            _operate->getNodeByName("icon_bg")->setVisible(true);
                            _eventDispatcher->setEnabled(true);
                        }else if(i==num-2){
                            listView.getListView()->getInnerContainer()->runAction(MoveBy::create(0.7, Vec2(400,0)));
                        }
                    }), ActionHelper::getScaleBtnAction(), nullptr));
            }

            bg_1->setVisible(true);
        });
        
        
    }else {
        _operate->getNodeByName("btn_next")->setVisible(true);
    }
    
}

void DecorationLayer::freeClick(KDS::EventSprite* s,size_t index,KDS::MyScollView*) {
    if(index == 0) {
        if(_currentcategory == "cup" || _currentcategory == "straw"){
            auto cupDec = _operate->getNodeByName<Sprite*>(_currentcategory+"Dec");
            cupDec->setVisible(false);
            FoodData::getDecoration(_currentcategory);
        }else if(_currentcategory == "sprinkle"){
            currentSprinkle = nullptr;
        }
        stopPrompt();
        auto path = FoodData::getDecorationPath(_currentcategory, 0);
        CocosHelper::visitAllNode(eatContainer, [this](Node* node){
            if(node->getName() == _currentcategory+"dec")
                node->removeFromParent();
        });
        
        SoundPlayer::getInstance()->playEffect("sound/7.reset.mp3");
        return ;
    }
    index--;
    auto path = FoodData::getDecorationPath(_currentcategory, index);
    SoundPlayer::getInstance()->playEffect("sound/choose.mp3");
    stopPrompt();
    if(_currentcategory == "candy"|| _currentcategory == "fruit") {
        showTouchPrompt();
        eatContainer->removeComponent("TouchNodeComponent");
        auto touch = TouchNodeComponent::create();
        touch->setSwallowTouches(true);
        touch->addListners(ComponentTouchEnd, [=](LQComponent*,OperateListner* lis){
            stopPrompt();
            playVoice();
            auto _s = Sprite::Sprite::create(path.at(0));
            auto pos = eatContainer->convertToNodeSpace(dynAny_cast<Vec2>(lis->getData()));
            SoundPlayer::getInstance()->playEffect("sound/general/decoration_tap.mp3");
            _s->setRotation(rand()%360);
            _s->setName(_currentcategory+"dec");
            eatClippinNode->addChild(_s);
            _s->setPosition(pos);
            _s->setScale(0);
            float _endScale = 0.6+rand()%3*0.1;
            if(_currentcategory == "fruit")
                _endScale*=0.8f;
            _s->runAction(ScaleTo::create(0.2, 0.8*_endScale/eatContainer->getScale()));
            
        });
        eatContainer->addComponent(touch);
        
        
    }else if(_currentcategory == "sprinkle"){
        if(currentSprinkle == nullptr){
            showTouchPrompt();
            currentSprinkle  = AddSprinkle::create();
            currentSprinkle->touchCallBack = [this](Touch*){
                stopPrompt();
                SoundPlayer::getInstance()->playEffect("sound/general/decoration_sprinkle.mp3");
            };
            currentSprinkle->setSwallowTouches(true);
            currentSprinkle->setName(_currentcategory+"dec");
            eatClippinNode->addChild(currentSprinkle);
            _operate->getNodeByName("spinkleTemp")->setVisible(true);
            currentSprinkle->caculatePos();
            _operate->getNodeByName("spinkleTemp")->setVisible(false);
        }
        if(currentSprinkle)
            currentSprinkle->setSprinklePath(path);
        currentSprinkle->setEnable(true);
    }else if( _currentcategory == "straw") {
        _eventDispatcher->setEnabled(false);
        auto strawUILayer = _operate->getNodeByName("strawUILayer");
        Sprite* tempSprite = Sprite::create(path.at(0));
        tempSprite->setPosition(strawUILayer->convertToNodeSpace(s->convertToWorldSpace(tempSprite->getContentSize()*.5)));
        strawUILayer->addChild(tempSprite);
        tempSprite->setScale(0.2f);
        tempSprite->runAction(ScaleTo::create(1.4f, 1));
        ActionHelper::delayFunc(0.9f, this, [=](){
            CocosHelper::reAddNode(tempSprite, _operate->getNodeByName("strawTempLayer"));
            _actionManager->resumeTarget(tempSprite);
        });
        auto cupDec = _operate->getNodeByName<Sprite*>("strawDec");
        Vec2 endPos;
        auto posPaht = FileUtils::getInstance()->fullPathForFilename(StringUtils::format("strawPos/%lu.csb",index));
        if(FileUtils::getInstance()->isFileExist(posPaht)){
            endPos = StudioLayer::create(posPaht)->getNodeByName("strawDec")->getPosition();
        }else {
             endPos = StudioLayer::create("strawPos/0.csb")->getNodeByName("strawDec")->getPosition();
        }
        tempSprite->runAction(Sequence::create(JumpTo::create(1.4f, strawUILayer->convertToNodeSpace(cupDec->getParent()->convertToWorldSpace(endPos)), 400, 1),CallFunc::create([=](){
            this->addParicle(tempSprite->getPosition());
            cupDec->setVisible(true);
            FoodData::eraseDecoration("straw");
            FoodData::addDecoration("straw", cupDec);
            cupDec->setSpriteFrame(tempSprite->getSpriteFrame());
            cupDec->setPosition(endPos);
            tempSprite->removeFromParent();
            _eventDispatcher->setEnabled(true);
        }), nullptr));
    }else if(_currentcategory == "cup"){
        _eventDispatcher->setEnabled(false);
        Sprite* tempSprite = Sprite::create(path.at(0));
        auto s1 = Sprite::createWithSpriteFrame(_operate->getNodeByName<Sprite*>("cupDown")->getSpriteFrame());
        s1->setPosition(tempSprite->getContentSize()*.5);
        tempSprite->addChild(s1,-2);
        s1 = Sprite::createWithSpriteFrame(_operate->getNodeByName<Sprite*>("cupUp")->getSpriteFrame());
        s1->setPosition(tempSprite->getContentSize()*.5);
        tempSprite->addChild(s1,-1);
        tempSprite->setPosition(s->convertToWorldSpace(s->getContentSize()*.5));
        this->addChild(tempSprite);
        tempSprite->setScale(0.2f);
        tempSprite->runAction(ScaleTo::create(0.8f*1.2, 1));
        auto cupDec = _operate->getNodeByName<Sprite*>("cupDec");
        tempSprite->runAction(Sequence::create(JumpTo::create(0.8f*1.2, cupDec->convertToWorldSpace(cupDec->getContentSize()*.5), 200, 1),CallFunc::create([=](){
            this->addParicle(tempSprite->getPosition());
            cupDec->setVisible(true);
            FoodData::eraseDecoration("cup");
            FoodData::addDecoration("cup", cupDec);
            cupDec->setSpriteFrame(tempSprite->getSpriteFrame());
            tempSprite->removeFromParent();
            _eventDispatcher->setEnabled(true);
        }), nullptr));
    }
}

void DecorationLayer::reset(){
    SoundPlayer::getInstance()->playEffect("sound/7.reset.mp3");
    Director::getInstance()->replaceScene(DecorationLayer::createScene());
}

void DecorationLayer::playVoice(){
    vector<string> paths = {
        "sound/Voice Over/tasty.mp3",
        "sound/Voice Over/yummy.mp3"
    };
    
    if(voiceSound%8==0){
        voiceSound = 0;
        SoundPlayer::getInstance()->playEffect(paths.at(rand()%paths.size()));
    }
    voiceSound++;
}
KDS::MyBaseAdapter* DecorationLayer::createAdapter(const string& _currentcategory){
    return MyBaseAdapter::create(FoodData::getIconPath(_currentcategory));
}

void DecorationLayer::addParicle(const Vec2& v){
    auto paticle = ParticleSystemQuad::create("particles/decorateParticle.plist");
    paticle->setPosition(v);
    paticle->setBlendFunc({GL_ONE_MINUS_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA});
    addChild(paticle,30);
    SoundPlayer::getInstance()->playEffect("sound/general/draw_success.mp3");
}

void DecorationLayer::showTouchPrompt(){
    auto down  = _operate->getNodeByName("down");
    _prompt->stopAllActions();
    _prompt->setPosition(_prompt->getParent()->convertToNodeSpace(_operate->getPosinWord(down->getName())));
    down->stopAllActions();
    _prompt->runAction(ActionHelper::createUpDownPrompt());
    _prompt->setVisible(true);
    down->setScale(0);
    down->runAction(RepeatForever::create(Sequence::create(DelayTime::create(0.3),ScaleTo::create(0.5, 1),DelayTime::create(0.1),ScaleTo::create(0, 0.3), nullptr)));
    down->setVisible(true);
}

void DecorationLayer::stopPrompt(){
    BaseDecorationLayer::stopPrompt();
    auto down  = _operate->getNodeByName("down");
    down->stopAllActions();
    down->setVisible(false);
}
